import React, {Component} from "react";
import {Card, Button, Icon, Table, message, Modal} from 'antd';
import LinkButton from "../../components/link-button";
import {reqCategorys, reqAddCategory, reqUpdateCategory} from '../../api/index';
import AddForm from "./add-form";
import UpdateForm from "./update-form";

/*
商品分类路由
 */
export default class Category extends Component {
    state = {
        loading: false,
        categorys: [],
        subCategorys: [],
        parentId: '0',
        parentName: '',
        showStatus: 0//0-不显示，1-添加，2-更新
    };

    initColumns = () => {
        this.columns = [
            {
                title: '分类名称',
                dataIndex: 'name'
            },
            {
                title: '操作',
                width: 300,
                render: (category) => (
                    <span>
                        <LinkButton onClick={()=>this.showUpdate(category)}>修改分类</LinkButton>
                        {
                            this.state.parentId === '0' ? (<LinkButton onClick={() => this.showSubCategorys(category)}>查看子分类</LinkButton>):null
                        }
                    </span>
                )
            }
        ];
    };

    getCategorys = async (pId) => {
        this.setState({loading: true});
        const parentId = pId || this.state.parentId;
        const result = await reqCategorys(parentId);
        this.setState({loading: false});
        if (result.status === 0) {
            const categorys = result.data;
            if (parentId === '0') {
                this.setState({categorys});
            } else {
                this.setState({subCategorys: categorys});
            }
        } else {
            message.error('获取分类数据失败')
        }
    };

    showCategorys = () => {
        this.setState({
            subCategorys: [],
            parentId: '0',
            parentName: ''
        })
    };

    showSubCategorys = (category) => {
        // state更新是推迟的，callback会在更新完成后执行
        this.setState(
            {parentId: category._id, parentName: category.name}, ()=>{this.getCategorys()}
        );
    };

    showAdd = () => {
        this.setState({showStatus: 1});
    };

    showUpdate = (category) => {
        this.category = category;
        this.setState({showStatus: 2});
    };

    addCategory = () => {
        this.form.validateFields(async (err, values) => {
            if (!err) {
                this.setState({showStatus: 0});

                const {parentId, categoryName} = values;

                this.form.resetFields();
                const result = await reqAddCategory(parentId, categoryName);
                if (result.status === 0) {
                    message.success('创建成功');
                    if (parentId === this.state.parentId) {
                        this.getCategorys();
                    } else if (parentId === '0') {
                        this.getCategorys('0');
                    }
                } else {
                    message.error('创建失败');
                }
            }
        });
    };

    updateCategory = () => {
        this.form.validateFields(async (err, values) => {
            if (!err) {
                this.setState({showStatus: 0});
                const categoryId = this.category._id;
                const {categoryName} = values;
                this.form.resetFields();

                const result = await reqUpdateCategory({categoryId, categoryName});
                if (result.status === 0) {
                    message.success('更新成功');
                    this.getCategorys();
                } else {
                    message.error('更新失败');
                }
            }
        });
    };

    handleCancel = () => {
        this.form.resetFields();
        this.setState({showStatus: 0});
    };

    componentWillMount() {
        this.initColumns();
    }

    componentDidMount() {
        this.getCategorys();
    }

    render() {
        const {categorys, loading, subCategorys, parentId, parentName, showStatus} = this.state;
        const category = this.category || {};

        const title = parentId === '0' ? '一级分类列表' : (
            <span>
                <LinkButton onClick={this.showCategorys}>一级分类列表</LinkButton>
                <Icon type='arrow-right' style={{marginRight: 5}}/>
                <span>{parentName}</span>
            </span>
        );
        const extra = (
            <Button type='primary' onClick={this.showAdd}>
                <Icon type='plus'/>
                添加
            </Button>
        );

        return (
            <div>
                <Card title={title} extra={extra}>
                    <Table
                        dataSource={parentId === '0' ? categorys : subCategorys}
                        columns={this.columns}
                        loading={loading}
                        bordered
                        rowKey='_id'
                        pagination={{defaultPageSize:5, showQuickJumper:true}}
                    />

                    <Modal
                        title="添加分类"
                        visible={showStatus === 1}
                        onOk={this.addCategory}
                        onCancel={this.handleCancel}
                        okText="确定"
                        cancelText="取消"
                    >
                        <AddForm categorys={categorys} parentId={parentId} setForm={(form)=>{this.form = form}}/>
                    </Modal>

                    <Modal
                        title="修改分类"
                        visible={showStatus === 2}
                        onOk={this.updateCategory}
                        onCancel={this.handleCancel}
                        okText="确定"
                        cancelText="取消"
                    >
                        <UpdateForm categoryName={category.name} setForm={(form)=>{this.form = form}}/>
                    </Modal>
                </Card>
            </div>
        );
    }
}